package com.lagou.flink.work.p6;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * 功能描述：
 *
 * @author : zhangyong
 * @since : 2021/5/18
 */
public class TableWork {

    public static void main(String[] args) throws Exception {
        //env
        StreamExecutionEnvironment env =
                StreamExecutionEnvironment.getExecutionEnvironment();
        //tEnv
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        DataStreamSource<Tuple2<String, Integer>> data = env.addSource(new SourceFunction<Tuple2<String, Integer>>() {
            @Override
            public void run(SourceContext<Tuple2<String, Integer>> sourceContext) throws Exception {
                while (true) {
                    sourceContext.collect(new Tuple2<String, Integer>("name", 10));
                    Thread.sleep(1000);
                }
            }
            @Override
            public void cancel() {

            }
        });

        //TABLE方式
        Table table = tEnv.fromDataStream(data, $("name"), $("age"));
        Table name = table.select($("name"));
        DataStream<Tuple2<Boolean, Row>> result = tEnv.toRetractStream(name, Row.class);
        result.print();
        //sql方式
        String s = "select name from userss";
        Table table1 = tEnv.sqlQuery(s);
        DataStream<Tuple2<Boolean, Row>> result1 = tEnv.toRetractStream(table1, Row.class);
        result1.print();
        env.execute();
    }
}
